#pragma once

#include <iostream>
#include <unordered_map>
#include <string>
#include <fstream>

#include "Common.hpp"

static const std::string path = "./";                          // 字典文件路径
static const std::string file_name = "CompleteDictionary.txt"; // 字典名
static const std::string split = ":";                          // 分隔符

namespace DictionaryArea
{
    using namespace LogArea;
    class Dictionary
    {
    private:
        bool SplitString(std::string word, std::string& key, std::string& val, const std::string split)
        {
            // 找不到分隔符, 返回 false
            size_t pos = word.find(split);
            if (pos == word.size())
                return false;

            key = word.substr(0, pos);
            val = word.substr(pos + split.size());
            return true;
        }

        void LoadDictionary()
        {
            std::string file = path + file_name;
            // 打开文件,按照流的方式读取、写入
            std::ifstream infile(file.c_str());
            if (!infile.is_open())
            {
                LOG(LogLevel::ERROR) << "infile.open() error";
                DIE(FILE_OPEN_ERROR);
            }

            // 从文件中按行读取数据
            std::string word;
            while (std::getline(infile, word))
            {
                std::string key;
                std::string val;
                if (SplitString(word, key, val, split));
                _dict[key] = val;
            }

            infile.close();
        }

    public:
        Dictionary() : _path(path), _file_name(file_name)
        {
            // 加载字典(_dict)
            LoadDictionary();

        }

        //查询字典
        std::string TranslateWord(const std::string& word)
        {
            auto it = _dict.find(word);
            if(it==_dict.end())
                return "None Find";
            return it->second;
        }

        void Print()
        {
            for (auto &it : _dict)
                std::cout << "key: " << it.first << " -> val: " << it.second << std::endl;
        }

    private:
        std::unordered_map<std::string, std::string> _dict;
        const std::string _path; // 字典文件路径
        const std::string _file_name;
    };
}